package com.bionic.ce.validators;

import com.bionic.ce.entities.User;
import com.bionic.ce.entitybeans.user.UserFacadeLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

@FacesValidator("com.bionic.ce.validators.NewUserValidator")
@EJB(name = "UsersFacadeLoc", beanInterface = UserFacadeLocal.class)
public class NewUserValidator implements Validator {

    private UserFacadeLocal userEJB = null;

    public NewUserValidator() {
    }

    @Override
    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {
        userEJB = lookupUsersFacadeLocal();
        String email = (String) value;
        User exsistingUser = new User();
        exsistingUser.setEmail(email);

        if (!userEJB.findByDynamicSelect(exsistingUser).isEmpty()) {
            FacesMessage msg =
                    new FacesMessage("Such e-mail is already registered.",
                    "Such e-mail is already registered.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }

    private UserFacadeLocal lookupUsersFacadeLocal() {
        try {
            Context c = new InitialContext();
            return (UserFacadeLocal) c.lookup("java:comp/env/UsersFacadeLoc");
        } catch (NamingException ex) {
            Logger.getLogger(NewUserValidator.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex);
        }
    }
}